package com.dzl.cardsecret;

import com.alibaba.fastjson.JSONObject;
import com.dzl.base.controller.BaseController;
import com.dzl.card.pojo.vo.WelfareCardExchangeSecretVo;
import com.dzl.card.pojo.vo.WelfareUserCardSecretVo;
import com.dzl.card.service.WelfareCardSecretService;
import com.dzl.constant.SmsTypeConstant;
import com.dzl.userwx.pojo.WelfareUserWx;
import com.dzl.userwx.service.WelfareUserWxService;
import com.dzl.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 卡密信息表(WelfareCardSecret)表控制层
 * @author ChenLong
 * @since 2021-05-14 20:19:50
 */
@Slf4j
@RestController
@RequestMapping("welfareCardSecret")
public class WelfareCardSecretController extends BaseController {
    @Autowired
    private WelfareCardSecretService welfareCardSecretService;
    @Autowired
    private WelfareUserWxService welfareUserWxService;

    /**
     * 增加用户绑定卡和手机号
     * @param jsonParams 用户id、卡密、电话、验证码
     * @return com.dzl.util.JsonResult
     * @author ChenLong
     * @since 2021-05-17 09:23:09
     **/
    @PostMapping("addUserCardAndPhoneBind")
    public JsonResult<Integer> addUserCardAndPhoneBind(@RequestBody JSONObject jsonParams) {
        log.info("addUserCardAndPhoneBind in jsonParams: " + jsonParams);
        Integer userId = getWxUserInfo().getId();
        String cardSecret = jsonParams.getString("cardSecret");
        String phone = jsonParams.getString("phone");
        String code = jsonParams.getString("code");
        // 电话号码不能为空
        if (EmptyUtils.isEmpty(phone)) {
            return JsonResult.paramErrWithMsgAndCode(1026, "请输入手机号码");
        }
        // 卡密不能为空
        if (EmptyUtils.isEmpty(cardSecret)) {
            return JsonResult.paramErrWithMsgAndCode(1025, "请输入卡密");
        }
        // 获取session验证码
        // todo：pro SmsTypeConstant.SMS_TYPE_BIND_CARD
        String sessionCode = (String) RedisUtil.get(phone + ":" + SmsTypeConstant.SMS_TYPE_BIND_NORMAL);
        // 验证码校验
        if (EmptyUtils.isEmpty(sessionCode) || !code.equals(sessionCode)) {
            return JsonResult.paramErrWithMsgAndCode(1027, "验证码错误，请重新获取");
        }
        // 校验该手机号是否已被绑定
        WelfareUserWx welfareUserWxSelect = new WelfareUserWx();
        welfareUserWxSelect.setPhone(phone);
        welfareUserWxSelect.setEnterpriseId(getWxUserInfo().getEnterpriseId());
        Integer phoneCount = welfareUserWxService.selectCount(welfareUserWxSelect);
        if (phoneCount > 0) {
            return JsonResult.paramErrWithMsgAndCode(1026, "该手机号已被绑定");
        }
        // 添加该用户绑定手机号
        WelfareUserWx welfareUserWx = new WelfareUserWx();
        welfareUserWx.setId(userId);
        welfareUserWx.setPhone(phone);
        welfareUserWx.setUpdateTime(new Date());
        Map<String, Object> resMap = welfareCardSecretService.addUserCardAndPhoneBind(welfareUserWx, cardSecret);
        if (resMap.get("code").equals(1)) {
            return JsonResult.success();
        } else {
            return JsonResult.failWithMsg(resMap.get("msg").toString());
        }
    }

    /**
     * 增加用户绑定卡
     * @param cardSecret 卡密
     * @return com.dzl.util.JsonResult
     * @author ChenLong
     * @since 2021-05-17 10:20:47
     **/
    @PostMapping("addUserCardBind")
    public JsonResult<Integer> addUserCardBind(String cardSecret) {
        log.info("addUserCardBind in cardSecret: " + cardSecret);
        Integer userId = getWxUserInfo().getId();
        // 卡密不能为空
        if (EmptyUtils.isEmpty(cardSecret)) {
            return JsonResult.paramErrWithMsgAndCode(1025, "请输入卡密或兑换券信息");
        }
        Map resMap = welfareCardSecretService.addUserCardBind(cardSecret, userId,getWxUserInfo().getEnterpriseId());
        if (resMap.get("code").equals(1)) {
            return JsonResult.success();
        } else {
            return JsonResult.failWithMsg(resMap.get("msg").toString());
        }
    }

    /**
     * 通过密钥获取卡或兑换券信息
     * @return com.dzl.util.JsonResult
     * @author ChenLong
     * @date 2021-07-10 11:09:42
     **/
    @GetMapping("getCardExchangeInfoBySecret")
    public JsonResult<WelfareCardExchangeSecretVo> getCardExchangeInfoBySecret(String secret) {
        log.info("getCardExchangeInfoBySecret in secret: " + secret);
        // 卡密不能为空
        if (EmptyUtils.isEmpty(secret)) {
            return JsonResult.paramErrWithMsg("请输入卡密或兑换券信息");
        }
        // 获取卡密和兑换券集合
        List<WelfareCardExchangeSecretVo> list = welfareCardSecretService.getCardExchangeInfoBySecret(secret);
        if (EmptyUtils.isEmpty(list) || list.size() < 1) {
            return JsonResult.paramErrWithMsgAndCode(1025,"请输入正确的卡密或兑换券信息");
        }
        if (list.size() > 1) {
            return JsonResult.failWithMsg("卡密或兑换券重复");
        }
        WelfareCardExchangeSecretVo welfareCardExchangeSecretVo = list.get(0);
        if (EmptyUtils.isNotEmpty(welfareCardExchangeSecretVo.getStatus()) && welfareCardExchangeSecretVo.getIsBind().equals(1)) {
            return new JsonResult<>(welfareCardExchangeSecretVo, 1025, "该卡密（兑换券）已被绑定");
        }
        if (EmptyUtils.isNotEmpty(welfareCardExchangeSecretVo.getIsExpired()) && welfareCardExchangeSecretVo.getIsExpired().equals(1)) {
            return new JsonResult<>(welfareCardExchangeSecretVo, 1025, "该卡密（兑换券）已过期");
        }
        if (EmptyUtils.isNotEmpty(welfareCardExchangeSecretVo.getIsActivate()) && welfareCardExchangeSecretVo.getIsActivate().equals(2)) {
            return new JsonResult<>(welfareCardExchangeSecretVo, 1025, "该卡密（兑换券）已被冻结");
        }
        if (EmptyUtils.isNotEmpty(welfareCardExchangeSecretVo.getIsActivate()) && welfareCardExchangeSecretVo.getIsActivate().equals(0)) {
            return new JsonResult<>(welfareCardExchangeSecretVo, 1025, "该卡密（兑换券）未激活");
        }
        return JsonResult.success(welfareCardExchangeSecretVo);
    }

    /**
     * 获取用户绑定的福利卡
     * @return com.dzl.util.JsonResult
     * @author ChenLong
     * @since 2021-05-19 16:12:00
     **/
    @GetMapping("getUserCardBindList")
    public JsonResult<List<WelfareUserCardSecretVo>> getUserCardBindList() {
        log.info("getUserCardBindList in");
        Integer userId = getWxUserInfo().getId();
        List<WelfareUserCardSecretVo> welfareCardSecretList = welfareCardSecretService.getUserCardBindList(userId);
        if (EmptyUtils.isNotEmpty(welfareCardSecretList)) {
            welfareCardSecretList.forEach(welfareUserCardSecretVo -> {
                if (EmptyUtils.isNotEmpty(welfareUserCardSecretVo.getImg())) {
                    welfareUserCardSecretVo.setImg(ImageUtils.setImageSrc(welfareUserCardSecretVo.getImg()));
                }
            });
        }
        return JsonResult.success(welfareCardSecretList);
    }

    /**
     * 获取用户绑定的福利卡详情
     * @author ChenLong
     * @date 2021-09-29 17:08:06
     * @param cardSecretId 卡ID
     * @return com.dzl.util.JsonResult<com.dzl.card.pojo.vo.WelfareUserCardSecretVo>
     **/
    @GetMapping("getUserCardBindInfo")
    public JsonResult<WelfareUserCardSecretVo> getUserCardBindInfo(Integer cardSecretId) {
        log.info("getUserCardBindInfo in");
        WelfareUserCardSecretVo welfareUserCardSecretVo = welfareCardSecretService.getUserCardBindInfo(cardSecretId);
        if (EmptyUtils.isNotEmpty(welfareUserCardSecretVo)) {
            welfareUserCardSecretVo.setImg(ImageUtils.setImageSrc(welfareUserCardSecretVo.getImg()));
        }
        return JsonResult.success(welfareUserCardSecretVo);
    }
}
